<template>
  <div
    class="vk-input"
    :class="{
      [`vk-input--${type}`]: type,
      [`vk-input--${size}`]: size,
      'is-disabled': disabled,
      'is-prepend': $slots.prepend,
      'is-append': $slots.append,
      'is-prefix': $slots.prefix,
      'is-suffix': $slots.suffix,
      'is-focus': isFocus
    }">
    <!-- input -->
    <template v-if="type !== 'textarea'">
      <!-- prepend slot -->
      <div v-if="$slots.prepend" class="vk-input__prepend">
        <slot name="prepend" />
      </div>
      <div class="vk-input__wrapper">
        <!-- prefix slot -->
        <span v-if="$slots.prefix" class="vk-input__prefix">
          <slot name="prefix" />
        </span>
        <input
          v-model="model"
          class="vk-input__inner"
          :type="type"
          :disabled="disabled"
          @focus="handleFocus"
          @blur="handleBlur" />
        <!-- suffix slot -->
        <span v-if="$slots.suffix || showClear" class="vk-input__suffix">
          <slot name="suffix" />
          <Icon
            icon="circle-xmark"
            v-if="showClear"
            class="vk-input__clear"
            @click="clear" />
        </span>
      </div>
      <!-- append slot -->
      <div v-if="$slots.append" class="vk-input__append">
        <slot name="append" />
      </div>
    </template>
    <!-- textarea -->
    <template v-else>
      <textarea
        class="vk-textarea__wrapper"
        :disabled="disabled"
        v-model="model" />
    </template>
  </div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { InputProps } from './type'
import Icon from '../Icon/Icon.vue'
const model = defineModel<string>()
defineOptions({
  name: 'VkInput'
})
const props = withDefaults(defineProps<InputProps>(), { type: 'text' })
const showClear = computed(
  () => props.clearable && !props.disabled && !!model.value && isFocus.value
)
const isFocus = ref(false)
const handleFocus = () => {
  isFocus.value = true
}
const handleBlur = () => {
  isFocus.value = false
}
const clear = () => {
  model.value = ''
}
</script>
